package com.yimi.yinhepda.views.load_module;

import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.yimi.yinhepda.R;
import com.yimi.yinhepda.adapter.LoadTaskAdapter;
import com.pda.ym.callbacks.UICallBack;
import com.yimi.yinhepda.db.dao.DepartmentTableDao;
import com.yimi.yinhepda.db.dao.UnloadScanTableDao;
import com.pda.ym.db.table.UnloadScanTable;
import com.yimi.yinhepda.db.table.DepartmentTable;
import com.yimi.yinhepda.entity.LoadTaskEntity;
import com.yimi.yinhepda.entity.bean.BaseDictEntity;
import com.yimi.yinhepda.entity.request.QueryLoadTaskRequest;
import com.yimi.yinhepda.entity.response.QueryBaseDictResponse;
import com.yimi.yinhepda.entity.response.QueryLoadTask;
import com.yimi.yinhepda.entity.response.QueryLoadTaskResponse;
import com.pda.ym.net.NetRequest;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.Constants;
import com.pda.ym.utils.FastClick;
import com.pda.uce.commom.util.MyDialog;
import com.pda.ym.utils.SharedPreferUtil;
import com.pda.ym.utils.SoundVibratorManager;
import com.pda.ym.utils.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 出发装车任务界面
 *
 * @author 000432
 */
public class LoadTaskActivity extends LoadBaseActivity {
    /**
     * 装车任务列表listview
     */
    private ListView listview;
    private List<LoadTaskEntity> dataList = new ArrayList<>();
    private LoadTaskAdapter loadTaskAdapter;
    private boolean isLoadData = false;
    /**
     * 合并装卸车
     */
    private List<BaseDictEntity> mDictCombind;

    public LoadTaskActivity() {
        super(true);
    }

    @Override
    protected void handleBarCode(String result) {
        if (!StringUtils.isCarCodeNo(result)) {
            SoundVibratorManager.playSound(2);
            showToast("配载单号不规范!");
            return;
        }

        for (LoadTaskEntity item : dataList) {
            item.setChecked(false);
        }

        boolean hasCheck = false;
        for (LoadTaskEntity item : dataList) {
            if (item.getCarCode().equals(result)) {
                item.setChecked(true);
                hasCheck = true;
                loadTaskAdapter.notifyDataSetChanged();
                break;
            }
        }

        if (hasCheck) {
            SoundVibratorManager.playSound(1);
            executeFunction();
        } else {
            SoundVibratorManager.playSound(2);
            showToast("没有对应的配载单！");
        }
    }

    @Override
    public String getPageName() {
        return "装车任务列表";
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loading_task_list);
        initView();
        //查询数据字典：合并装卸车（combind_load_unload）
        queryDictCombindLoadUnload();
    }

    @Override
    protected void onResume() {
        super.onResume();
        boolean flag = sharedPreferUtil.getBooleanValue(Common.SUCCESS_SUBMIT_LOAD);
        if (flag) {
            loadData();
        }
        //设置未上传数
        num.setText((int) mUnloadScanTableDao.queryCount("isUpload", 0, operTypeCode) + "");
    }

    /**
     * 查询数据字典：合并装卸车（combind_load_unload）
     */
    private void queryDictCombindLoadUnload() {
        showPgDlg("正在加载配置...");
        Map<String, String> params = new HashMap<>(2);
        params.put("dictCode", "combind_load_unload");
        //查询类型，1-只查询未作废的，为null则查询所有(包含作废和未作废的)
        params.put("type", "1");

        new NetRequest().setMethod(NetRequest.Method.GET)
                .setResponsClazz(QueryBaseDictResponse.class)
                .setUrl(Constants.URL_QUERY_DICT)
                .setParams(params)
                .setConnTimeOut(10 * 1000)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        showToast(msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        QueryBaseDictResponse response = (QueryBaseDictResponse) obj;
                        if (response != null && response.getData() != null) {
                            mDictCombind = response.getData();
                        }
                        loadData();
                    }
                });
    }

    private void initView() {
        ((TextView) findViewById(R.id.title)).setText("装车任务列表");
        num = (TextView) findViewById(R.id.num);
        listview = (ListView) findViewById(R.id.load_task_listview);
        findViewById(R.id.load_task_back).setOnClickListener(this);
        findViewById(R.id.load_task_refresh).setOnClickListener(this);
        findViewById(R.id.load_task_execute).setOnClickListener(this);
    }

    private void loadData() {
        if (isLoadData) {
            return;
        }
        //关闭扫描
        setScannerEnabled(false);
        isLoadData = true;
        showPgDlg("正在加载数据...");
        QueryLoadTaskRequest mQueryLoadTaskRequest = new QueryLoadTaskRequest();
        //员工工号
        mQueryLoadTaskRequest.setOperEmpCode(SharedPreferUtil.getInstance().getValue(Common.USER_CODE));
        //mQueryLoadTaskRequest.setSrcDeptCode(SharedPreferUtil.getInstance().getValue(Common.DEPT_CODE));//所属部门
        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setResponsClazz(QueryLoadTaskResponse.class)
                .setUrl(Constants.QUERY_LOADTASK)
                .setRequestObject(mQueryLoadTaskRequest)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        isLoadData = false;
                        setScannerEnabled(true);
                        SoundVibratorManager.playSound(2);
                        showToast("加载数据失败:" + msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        isLoadData = false;
                        setScannerEnabled(true);
                        if (obj instanceof QueryLoadTaskResponse) {
                            QueryLoadTaskResponse response = (QueryLoadTaskResponse) obj;
                            if (response.getData() != null && response.getData().size() > 0) {
                                //数据转换
                                dataList.clear();
                                DepartmentTableDao departmentTableDao = new DepartmentTableDao();
                                UnloadScanTableDao mUnloadScanTableDao = new UnloadScanTableDao();
                                for (QueryLoadTask item : response.getData()) {
                                    //查找本地已扫票数
                                    List<UnloadScanTable> list = mUnloadScanTableDao.getStowageNoData(item.getStowageNo());
                                    String task = Constants.getUUID();
                                    if (list != null && list.size() > 0) {
                                        for (UnloadScanTable temp : list) {
                                            if (temp.getTask() != null) {
                                                task = temp.getTask();
                                            }
                                        }
                                    }
                                    //查询跨越虚拟网点
                                    DepartmentTable departmentTable = departmentTableDao.getDataByDeptType(item.getDestDeptCode(), "7");
                                    dataList.add(new LoadTaskEntity(task, item.getStowageNo(), item.getCarMark(), item.getSrcDeptCode(), item.getSrcDeptName(), item.getDestDeptName(),
                                            item.getDestDeptCode(), item.getCarNo(), item.getPriceNum() + "", item.getBizTypeCode(), false, item.getPreStartDate(),
                                            item.getLoadingLimit(), item.getLoadingProduct(), item.getCarModel(), departmentTable != null ? 1 : 0));
                                }
                            } else {
                                //SoundVibratorManager.playSound(2);
                                showToast("没有配载单!");
                                dataList.clear();
                            }
                            loadTaskAdapter = new LoadTaskAdapter(LoadTaskActivity.this, dataList, LoadTaskActivity.this);
                            //设置需要合并装车的数据
                            loadTaskAdapter.setDictCombind(mDictCombind);
                            listview.setAdapter(loadTaskAdapter);
                        }
                    }
                });
    }

    @Override
    public void onClick(View v) {
        if (FastClick.isFastClick()) {
            return;
        }
        super.onClick(v);
        switch (v.getId()) {
            case R.id.load_task_back:
                finish();
                break;
            case R.id.load_task_refresh:
                loadData();
                break;
            case R.id.load_task_execute:
                executeFunction();
                break;
            default:
                break;
        }
    }

    /**
     * 执行方法
     */
    private void executeFunction() {
        if (loadTaskAdapter == null) {
            showToast("请选择一项任务执行");
            return;
        }

        final List<LoadTaskEntity> entites = loadTaskAdapter.getCheckJumpEntites();
        if (entites != null) {
            if (entites.size() > 1) {
                if (this.isFinishing()) {
                    return;
                }
                MyDialog dialog = new MyDialog(this);
                dialog.setIcon(R.drawable.alert);
                dialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
                dialog.setTitle("系统提示");
                dialog.setMessage("是否要多配载单合并装车？");
                dialog.setPositiveClickListener( "确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        toLoadUnloadGroupActivity(LoadTaskActivity.this, entites);
                    }
                });
                dialog.setNegativeClickListener(R.drawable.btn_login_selector, "取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                dialog.setCancelable(false);
                dialog.setCanceledOnTouchOutside(false);
                dialog.show();
            } else if (entites.size() > 0) {
                toLoadUnloadGroupActivity(LoadTaskActivity.this, entites);
            } else {
                showToast("请选择一项任务执行");
            }
        } else {
            showToast("请选择一项任务执行");
        }
    }
}
